package com.bootadmin.core.handler;

import javax.servlet.http.HttpServletRequest;

import com.bootadmin.core.excepiton.ServiceException;
import com.bootadmin.core.web.ResultJson;
import com.bootadmin.core.web.SystemConstant;

import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author kongzm
 * @description: BootAdminHandlerExceptionResolver
 * @date 2022/1/15 21:09
 */
@ControllerAdvice
@ResponseBody
public class BootAdminHandlerExceptionResolver{

    /**
     * 所有异常报错
     */
    @ExceptionHandler(value= ServiceException.class)
    public ResultJson allExceptionHandler(HttpServletRequest request,
                                      ServiceException exception) throws ServiceException
    {
        if (exception.getCode() == SystemConstant.LOGIN_FAILURE_CODE) {
            return ResultJson.failureLogin(exception.getMsg());
        } else if (exception.getCode() == SystemConstant.AUTH_FAILURE_CODE) {
            return ResultJson.failureAuth();
        } else if (exception.getCode() == SystemConstant.FAILURE_CODE) {
            return ResultJson.failure(exception.getMsg());
        } else {
            return ResultJson.failureSys(exception.getMessage());
        }
    }

    @ExceptionHandler(value= RuntimeException.class)
    public ResultJson runtimeExceptionHandler(HttpServletRequest request,
                                              RuntimeException exception) throws RuntimeException
    {
        exception.printStackTrace();
        return ResultJson.failureSys(exception.getMessage());
    }

    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public ResultJson missingExceptionHandler(HttpServletRequest request, MissingServletRequestParameterException exception) throws MissingServletRequestParameterException {
        // exception.printStackTrace();
        return ResultJson.failureSys("缺少必要参数:" + exception.getMessage());
    }
    
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultJson notSupportExceptionHandler(HttpServletRequest request, HttpRequestMethodNotSupportedException exception) throws HttpRequestMethodNotSupportedException {
        // exception.printStackTrace();
        return ResultJson.failureSys("不支持的请求方式:" + exception.getMessage());
    }
}
